package com.plupload.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/")
public class PluploadController {

	private static final String uploadDir="/UploadDir/";
	private static final int BUFFER_SIZE = 100 * 1024;
	private static final Logger logger = Logger.getLogger(PluploadController.class);
	
	@RequestMapping(value = "/")
	public ModelAndView index(HttpServletRequest request, HttpSession session) {
		return new ModelAndView("index", "fileList", getFileList(session));
	}

	private List<String> getFileList(HttpSession session){
		List<String> fileList=new ArrayList<String>();
		String realPath = session.getServletContext().getRealPath("");
		File folder = new File(realPath + uploadDir);
		if(folder.exists()){
			String files[]=folder.list();
			for(int i=0; i<files.length; i++){
				fileList.add(files[i]);
			}
		}
		return fileList;
	}

	/**
	 * 使用plupload上传文件
	 * @param file		文件对象
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="UploadBySpringMVC",method=RequestMethod.POST)
	public ModelAndView plupload(@RequestParam MultipartFile file, HttpServletRequest request, HttpSession session) {
		try {
			String name = file.getOriginalFilename();
			logger.info("file.originalFilename="+name);
			//检查文件目录，不存在则创建
			String realPath = session.getServletContext().getRealPath("");
			File folder = new File(realPath + uploadDir);
			if (!folder.exists()) {
				folder.mkdirs();
			}
			
			//目标文件 
			File destFile = new File(folder, name);
			//文件已存在删除旧文件（上传了同名的文件） 
	        if (destFile.exists()) {
	        	destFile.delete();  
	        	destFile = new File(folder, name);
	        }
	        //合成文件
	        appendFile(file.getInputStream(), destFile);
		} catch (IOException e) {
			logger.error(e.getMessage());
		}

		return new ModelAndView("index", "fileList", getFileList(session));
	}
	
	private void appendFile(InputStream in, File destFile) {
		OutputStream out = null;
		try {
			// plupload 配置了chunk的时候新上传的文件append到文件末尾
			if (destFile.exists()) {
				out = new BufferedOutputStream(new FileOutputStream(destFile, true), BUFFER_SIZE); 
			} else {
				out = new BufferedOutputStream(new FileOutputStream(destFile),BUFFER_SIZE);
			}
			in = new BufferedInputStream(in, BUFFER_SIZE);
			
			int len = 0;
			byte[] buffer = new byte[BUFFER_SIZE];			
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {		
			try {
				if (null != in) {
					in.close();
				}
				if(null != out){
					out.close();
				}
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
	}
	
}
